<template>
  <div class="">
    <ticket-tabbar :tabList="tabList" :currentTab="currentTab" @change="tabChange"></ticket-tabbar>

    <scroll-view
      refresher-enabled
      scroll-y="true"
      @refresherrefresh="reload"
      :refresher-triggered="triggered"
      :style="{ height: screenHeight }"
      @scrolltolower="loadData"
      class=""
    >
      <div class="wrap" style="padding-top: 20rpx">
        <order-item :isGw="currentTab == 1" v-for="(item, index) in list" :key="item.id" :item="item"> </order-item>
      </div>
      <uni-load-more :status="loading ? 'loading' : noMore ? 'noMore' : 'more'" />
    </scroll-view>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, watch, computed, defineExpose } from 'vue'
import { useStore } from 'vuex'
import OrderItem from './order-item.vue'
const store = useStore()
const screenHeight = ref<number>(0)
const statusBarHeight = computed(() => store.getters['system/statusBarHeight'])
const bottomSafeArea = computed(() => store.getters['system/bottomSafeArea'])
screenHeight.value = `calc(100vh - ${statusBarHeight.value}px - ${bottomSafeArea.value}px - 90rpx - 116rpx - 126rpx - 64rpx)`

import { orderList } from '@/utils/api/order'

// 请求状态码，是否又更多
const loading = ref<boolean>(false)
const noMore = ref<boolean>(false)
interface TabItem {
  value: number
  label: string
}

let tabList = reactive<TabItem[]>([
  {
    value: 1,
    label: '当前 Current'
  },
  {
    value: 2,
    label: '过往 Previous'
  }
])
// 订单列表
let list = ref<any[]>([])
// triggered:刷新的状态
let triggered = ref<boolean>(false)

// 显式声明并赋值
let current: number = 1
// 当前tab选项卡
let currentTab = ref<number>(0)

// 是否是重新加载
let isReload: boolean = false

const loadData = async () => {
  if (loading.value || noMore.value) {
    return
  } else {
    loading.value = true
  }

  const res = await orderList({
    current: current,
    clientStatus: tabList[currentTab.value].value,
    size: 10
  })
  loading.value = false
  triggered.value = false
  console.log('刷新状态:', triggered.value)
  uni.stopPullDownRefresh()
  if (res.code === 200) {
    if (res.data.next) {
      current++
      noMore.value = false
    } else {
      noMore.value = true
    }
    if (isReload) {
      list.value = res.data.list
      isReload = false
    } else {
      list.value = list.value.concat(res.data.list)
    }
  }
}

const reload = () => {
  isReload = true
  triggered.value = true
  current = 1
  noMore.value = false
  loadData()
}
const tabChange = (index: number) => {
  currentTab.value = index
  console.log('接收到的下标', index)
  reload()
}
onMounted(() => {
  loadData()
})
defineExpose({
  reload
})
</script>

<style lang="scss" scoped>
@import './order.scss';
</style>
